package main

import (
	"embed"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"goadmin/logs"
	"goadmin/models"
	"goadmin/routers"
	"goadmin/utils"
	"goadmin/wechatMiniprogram"
	"html/template"
	"io/fs"
	"net/http"
	"time"
)

//go:embed templates/index.html
var tmplFS embed.FS

//go:embed templates/assets
var assetsFS embed.FS

func main() {
	//配置日志
	logs.InitLogger()
	defer logs.Sync()
	models.InitDB()
	//初始化微信配置
	wechatMiniprogram.InitWechat()

	logs.Info("app 启动")
	// 初始化验证器翻译
	utils.InitValidator()

	// 创建一个默认的路由引擎
	r := gin.Default()

	//配置gin允许跨域请求
	r.Use(cors.New(cors.Config{
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
		AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
		AllowCredentials: false,
		MaxAge:           12 * time.Hour,
		ExposeHeaders:    []string{"Content-Length"},
		AllowOriginFunc: func(origin string) bool {
			return true
		},
	}))
	//自定义模板函数  注意要把这个函数放在加载模板前
	r.SetFuncMap(template.FuncMap{
		"UnixToTime": utils.UnixToTime,
	})
	t := template.Must(
		template.ParseFS(tmplFS, "templates/*.html"),
	)
	r.SetHTMLTemplate(t)
	/* 2. 静态资源：把 embed 子目录做成 http.FS */
	// 去掉前缀“templates/assets”，得到纯 assets 文件系统
	assets, _ := fs.Sub(assetsFS, "templates/assets")
	r.StaticFS("/assets", http.FS(assets))

	routers.AdminRoutersInit(r)
	routers.ApiRoutersInit(r)
	routers.DefaultRoutersInit(r)
	// 创建WebSocket管理器
	wsManager := utils.GetWebSocketManager()
	// 启动一个定时任务，每10秒向所有客户端发送消息
	go func() {
		ticker := time.NewTicker(10 * time.Second)
		defer ticker.Stop()
		count := 1
		for range ticker.C {
			message := []byte("服务器定时消息,当前时间是" + utils.GetDate())
			wsManager.Broadcast(message)
			count++
		}
	}()
	r.GET("/ws", wsManager.HandleWebSocket) // WebSocket处理
	//启动定时任务执行
	utils.RunTasks()
	//启动http服务
	if err := r.Run(":8080"); err != nil {
		zap.S().Info("启动失败,失败原因为", err.Error())
	}
}
